package top.igotcha.chapter.chapter8.cyclicBarrier;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static java.lang.Thread.sleep;

/**
 * @author Gotcha
 * @date 2021/3/20
 * @describe
 */
@Slf4j(topic = "CyclicBarrierTest01")
public class CyclicBarrierTest01 {
    public static void main(String[] args) {
        ExecutorService pool = Executors.newFixedThreadPool(2);
        CyclicBarrier barrier = new CyclicBarrier(2);

        for (int i = 0;i<3;i++) {
            pool.execute(()->{
                log.debug("任务1开始");
                try {
                    sleep(1000);
                    barrier.await();//2-1=1
                    log.debug("任务1结束");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
            pool.execute(()->{
                log.debug("任务2开始");
                try {
                    sleep(2000);
                    barrier.await();//1-1=0
                    log.debug("任务2结束");
                } catch (InterruptedException | BrokenBarrierException e) {
                    e.printStackTrace();
                }
            });
        }
        pool.shutdown();
    }
}
